﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Net.Sockets;

using Giri;

namespace Giri.L1
{
    class Client
    {
        TcpClient client;
        NetworkStream stream;
        public Client(TcpClient client)
        {
            Open(client);
        }

        ~Client()
        {
            Close();
        }

        public void Send(L1.Message msg)
        {
            byte[] buffer = msg.GetMessageBytes();
            stream.Write(buffer, 0, buffer.Length);
        }

        public L1.Message Receive()
        {
            if (stream.DataAvailable)
            {
                byte[] buffer = new byte[1400];
                stream.Read(buffer, 0, 1400);
                return new L1.Message(buffer);
            }
            return null;
        }

        public void Open(TcpClient client)
        {
            this.client = client;
            stream = this.client.GetStream();
        }

        public void Close()
        {
            if (client.Connected)
            {
                stream.Close();
                client.Close();
                stream = null;
                client = null;
            }
        }
    }
}
